// src/utils/auth.js

export const TOKEN_KEY = 'auth_token'; // 唯一定义并导出

import service from './request';

export function getAuthToken() {
  return localStorage.getItem(TOKEN_KEY);
}

export function setAuthToken(token) {
  localStorage.setItem(TOKEN_KEY, token);
  service.defaults.headers.common['Authorization'] = `Bearer ${token}`;
}

export function clearAuthToken() {
  localStorage.removeItem(TOKEN_KEY);
  delete service.defaults.headers.common['Authorization'];
}

export function isAuthenticated() {
  return !!getAuthToken();
}

// login 发送 POST /api/v1/auth/login
export async function login(username, password) {
  return service.post('/auth/login', { username, password }, {
    headers: { 'Content-Type': 'application/json' }
  });
}

export async function sendVerificationCode(phoneNumber, type) {
  return service.post('/auth/send-verification-code', { phoneNumber, type });
}

// 重置密码
export async function resetPassword(phoneNumber, verificationCode, newPassword) {
  return service.post('/auth/reset-password', { phoneNumber, verificationCode, newPassword });
}

export async function register(phoneNumber, password, role) {
  return service.post('/auth/register', { phoneNumber, password, role: role.toUpperCase() }, {
    headers: { 'Content-Type': 'application/json' }
  });
}

export async function getUserInfo() {
  console.log('请求用户信息时 token 是：', localStorage.getItem(TOKEN_KEY));
  return service.get('/user', {
    headers: {
      'Authorization': `Bearer ${getAuthToken()}`,
      'Cache-Control': 'no-cache',
      'Pragma': 'no-cache'
    }
  });
}
